import 'package:afmjb1/mjb/log_utls.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class TMWHttps {
  static const String kBaseUrl =
      'https://www.fastmock.site/mock/a1d675cbf7449ef9650e29b5b83aa2e9/data/';

  ///超时时间
  static const Duration kConnectTimeOut = Duration(seconds: 20);
  static const Duration kReceiveTimeOut = Duration(seconds: 20);

  /// 单例
  static TMWHttps instance = TMWHttps._internal();

  factory TMWHttps() => instance;

  final Dio _dio = Dio();
  final CancelToken _cancelToken = CancelToken();

  TMWHttps._internal() {
    _dio.options
      ..baseUrl = kBaseUrl
      ..connectTimeout = kConnectTimeOut
      ..receiveTimeout = kReceiveTimeOut
      ..validateStatus = (int? status) {
        return status != null && status > 0;
      }
      ..headers = {};
  }

  ///  get 操作
  Future<Map?> get(
    String path, {
    Map<String, dynamic>? params,
  }) async {
    EasyLoading.show();
    try {
      Response<Map<String, dynamic>> response =
          await _dio.get(path, queryParameters: params);
      EasyLoading.dismiss();
      printLog(response.data);

      return response.data;
    } on DioException catch (e) {
      printLog(e.message);
      EasyLoading.dismiss();
      return null;
    }
  }

  ///  post 操作
  Future<Map?> post(String path) async {
    EasyLoading.show();
    try {
      Response<Map<String, dynamic>> response = await _dio.post(path);
      EasyLoading.dismiss();
      printLog("response.data=" + response.data.toString());
      return response.data;
    } on DioException catch (e) {
      printLog(e.message);
      EasyLoading.dismiss();
      return null;
    }
  }
}
